package com.jianjun.project.system.login;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Inject;
import com.jfinal.i18n.I18n;
import com.jfinal.kit.ThreadPoolKit;
import com.jfinal.plugin.ehcache.UtilCache;
import com.jianjun.common.constant.CacheConstants;
import com.jianjun.common.constant.CommonAttribute;
import com.jianjun.common.constant.Constants;
import com.jianjun.common.constant.UserConstants;
import com.jianjun.common.enums.UserStatus;
import com.jianjun.common.exception.ServiceException;
import com.jianjun.common.exception.user.BlackListException;
import com.jianjun.common.exception.user.CaptchaException;
import com.jianjun.common.exception.user.CaptchaExpireException;
import com.jianjun.common.exception.user.UserNotExistsException;
import com.jianjun.common.exception.user.UserPasswordNotMatchException;
import com.jianjun.common.exception.user.UserPasswordRetryLimitExceedException;
import com.jianjun.common.util.AllConfig;
import com.jianjun.common.util.SecurityUtils;
import com.jianjun.common.util.ip.IpUtils;
import com.jianjun.framework.manager.factory.AsyncFactory;
import com.jianjun.framework.security.LoginUser;
import com.jianjun.framework.security.service.SysPermissionService;
import com.jianjun.framework.security.service.TokenService;
import com.jianjun.project.common.model.SysUser;
import com.jianjun.project.system.config.SysConfigService;
import com.jianjun.project.system.user.SysUserService;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;


/**
 * 登录校验方法
 *
 * @author source
 */
@Slf4j
public class SysLoginService {
    private final Integer maxRetryCount = AllConfig.CONFIG.getInt("user.password.maxRetryCount");
    private final Integer lockTime = AllConfig.CONFIG.getInt("user.password.lockTime");
    @Inject
    SysConfigService configService;
    @Inject
    SysPermissionService permissionService;
    @Inject
    SysUserService userService;
    @Inject
    TokenService tokenService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        SysUser user;
        try {
            SysUser model = new SysUser();
            model.setUserName(username);
            user = userService.selectUserFirst(model);
            if (Objects.isNull(user)) {
                log.info("登录用户：{} 不存在.", username);
                throw new ServiceException(I18n.use().format("user.not.exists"));
            } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                log.info("登录用户：{} 已被删除.", username);
                throw new ServiceException(I18n.use().format("user.password.delete"));
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                log.info("登录用户：{} 已被停用.", username);
                throw new ServiceException(I18n.use().format("user.blocked"));
            }

            Integer retryCount = Convert.toInt(UtilCache.get(getCacheKey(username)));

            if (retryCount == null) {
                retryCount = 0;
            }
            if (retryCount >= maxRetryCount) {
                throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
            }

            if (!matches(user, password)) {
                retryCount = retryCount + 1;
                Integer finalRetryCount = retryCount;
                UtilCache.setex(getCacheKey(username), lockTime * DateUnit.MINUTE.getMillis() / DateUnit.SECOND.getMillis(), Convert.toStr(finalRetryCount));
                throw new UserPasswordNotMatchException();
            } else {
                clearLoginRecordCache(username);
            }
        } catch (Exception e) {
            if (e instanceof UserPasswordNotMatchException) {
                ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18n.use().format("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, I18n.use().format("user.login.success")));
        recordLoginInfo(user);
        // 生成token
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StrUtil.nullToEmpty(uuid);
            String redisGet = UtilCache.get(verifyKey);
            String captcha = null;
            if (StrUtil.isNotEmpty(redisGet)) {
                captcha = StrUtil.unWrap(redisGet, CommonAttribute.PS, CommonAttribute.PS);
            }
            if (captcha == null) {
                ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18n.use().format("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            UtilCache.del(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18n.use().format("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18n.use().format("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18n.use().format("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18n.use().format("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            ThreadPoolKit.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18n.use().format("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser sysUser) {
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtil.date());
        sysUser.update();
    }

    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public boolean matches(SysUser user, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        if (UtilCache.exists(getCacheKey(loginName))) {
            UtilCache.del(getCacheKey(loginName));
        }
    }

}
